package com.example.demo.util;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTVerificationException;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.example.demo.DTO.ResultDTO;
import com.example.demo.entity.User;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.Date;


/**
 * @author moguai
 * @version 1.0
 * @date 2022/3/17 14:05
 */
@Component("TokenUtils")
public class TokenUtils {
    private static String SECRET;
    public static Long EXPIRE;

    @Value("${site.jwt.secret}")
    public void setSecret(String SECRET) {
        TokenUtils.SECRET = SECRET;
    }

    @Value("${TOKEN.EXPIRE}")
    public void setExpire(Long EXPIRE) {
        TokenUtils.EXPIRE = EXPIRE;
    }

    private TokenUtils tokenUtils;

    public String getToken(User user) {
        String token = "";
        token = JWT.create()
                .withClaim("name", user.getName())
                .withClaim("id", user.getId())
                .withClaim("email", user.getEmail())
                .withClaim("time", System.currentTimeMillis())
                .withIssuer("hik")
                .withExpiresAt(new Date(System.currentTimeMillis() + EXPIRE))
                .sign(Algorithm.HMAC256(SECRET));
        return token;
    }

    public static ResultDTO verifyToken(String token) {
        JWTVerifier jwtVerifier = JWT.require(Algorithm.HMAC256(SECRET)).build();
        try {
            DecodedJWT verify = jwtVerifier.verify(token);
            User user = new User();
            user.setId(verify.getClaim("id").asInt());
            user.setName(verify.getClaim("name").asString());
            user.setEmail(verify.getClaim("email").asString());
            return ResultDTO.okOf(user);
        } catch (JWTVerificationException e) {
            return ResultDTO.errorOf("token验证失败：" + e.getMessage());
        }
    }

    public static void setTokenWhite(String token, Integer id) {
        if (token != null && StringUtils.isNotEmpty(token)) {
            RedisUtil.setWhite(token, id);
        }

    }

    public static boolean isTokenWhite(String token) {
        if (token != null && StringUtils.isNotEmpty(token)) {
            return RedisUtil.keyIsExists(token);
        }
        return false;
    }

    public static void deleteTokenWhite(String token) {
        if (token != null) {
            RedisUtil.deleteWhite(token);
        }
    }

    public static void setTokenBlack(String token) {
        if (token != null) {
            RedisUtil.hset("blackList", token, Long.toString(System.currentTimeMillis()));
        }
    }

    public static Boolean isTokenBlack(String token) {
        if (token != null) {
            return RedisUtil.hasKey("blackList", token);
        }
        return false;
    }

}
